package com.jrx.anytxn.transaction.job.dailyAccount.step;

import com.jrx.anytxn.common.constant.Constants;
import com.jrx.anytxn.param.entity.PrOrganizationTable;
import com.jrx.anytxn.param.service.system.IOrganizationTableService;
import com.jrx.anytxn.transaction.constant.TransBizConstant;
import com.jrx.anytxn.transaction.entity.TlDailyAccountLog;
import com.jrx.anytxn.transaction.entity.TlDisbursementLog;
import com.jrx.anytxn.transaction.job.dailyAccount.bean.DailyAccountBean;
import com.jrx.anytxn.transaction.mapper.ext.ExtTlDailyAccountLogMapper;
import com.jrx.anytxn.transaction.mapper.ext.ExtTlDisbursementLogMapper;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.batch.item.ItemWriter;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * 日终T24核心汇总记账 更新放款流水表日终记账状态
 *
 * @Author yhy
 * @Date 2023/4/29 16:44
 */
@Service
public class DailyAccountWriter implements ItemWriter<DailyAccountBean> {

    @Resource
    private ExtTlDisbursementLogMapper extTlDisbursementLogMapper;

    @Resource
    private ExtTlDailyAccountLogMapper extTlDailyAccountLogMapper;

    @Resource
    private IOrganizationTableService iOrganizationTableService;

    @Override
    public void write(List<? extends DailyAccountBean> items) throws Exception {

        if(CollectionUtils.isNotEmpty(items)){
            for (DailyAccountBean dailyAccountBean : items){
                // 批量保存日终T24核心汇总记账明细流水
                List<TlDailyAccountLog> tlDailyAccountLogList = dailyAccountBean.getTlDailyAccountLogList();
                if (CollectionUtils.isNotEmpty(tlDailyAccountLogList)){
                    for (TlDailyAccountLog dailyAccountLog : tlDailyAccountLogList){
                        extTlDailyAccountLogMapper.insert(dailyAccountLog);
                    }
                }
                // 批量更新放款流水表中日终T24核心汇总记账状态
                List<TlDisbursementLog> tlDisbursementLogList = dailyAccountBean.getTlDisbursementLogList();
                if (CollectionUtils.isNotEmpty(tlDisbursementLogList)){
                    for (TlDisbursementLog disbursementLog : tlDisbursementLogList){
                        extTlDisbursementLogMapper.updateByPrimaryKeySelective(disbursementLog);
                    }
                }
            }
        }
        PrOrganizationTable org = iOrganizationTableService.findByOrgIdForBatch(TransBizConstant.DEFAULT_ORG_ID);
        // 更新当日进行退汇、抹账、取消等操作的订单
        extTlDisbursementLogMapper.updateCancelLogWithSameDate(Constants.DEFAULT_TENANT_ID, org.getToday());
    }
}
